import React, { useState, useEffect } from 'react';
import { Card, Row, Col, Tag, Button, Select, message, Space, Typography, Input, Divider } from 'antd';
import { CopyOutlined, CheckOutlined, SearchOutlined, ClearOutlined } from '@ant-design/icons';
import styled from '@emotion/styled';
import { Segment, useDefault } from 'segmentit';

const { Title, Text } = Typography;
const { Option } = Select;
const { TextArea } = Input;

// 定义数据类型
interface CategoryItem {
  zh: string;
  en: string;
  th: string;
}

interface Category {
  name: CategoryItem;
  items: CategoryItem[];
}

// 样式组件
const PageContainer = styled.div`
  padding: 16px;
  background: #f5f5f5;
  min-height: 100vh;
`;

const HeaderSection = styled.div`
  background: white;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
`;

const CategoryCard = styled(Card)`
  margin-bottom: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  
  .ant-card-head {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 6px 6px 0 0;
    padding: 8px 16px;
    min-height: auto;
    
    .ant-card-head-title {
      color: white;
      font-weight: 600;
      font-size: 16px;
    }
  }
  
  .ant-card-body {
    padding: 12px;
  }
`;

const ItemTag = styled(Tag)<{ selected: boolean }>`
  margin: 2px;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 12px;
  
  ${props => props.selected ? `
    background: #1890ff;
    color: white;
    border-color: #1890ff;
    transform: scale(1.05);
  ` : `
    background: white;
    color: #666;
    border-color: #d9d9d9;
    
    &:hover {
      background: #e6f7ff;
      border-color: #91d5ff;
      color: #1890ff;
      transform: translateY(-1px);
    }
  `}
`;

const ResultSection = styled.div`
  background: white;
  padding: 16px;
  border-radius: 6px;
  margin-top: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
`;

const ResultText = styled.div`
  background: #f6f8fa;
  border: 1px solid #e1e4e8;
  border-radius: 4px;
  padding: 12px;
  margin-top: 12px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-break: break-all;
  min-height: 80px;
`;

// 添加分词相关的样式组件
const SegmentSection = styled.div`
  background: white;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
`;

const SegmentInputArea = styled.div`
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px;
`;

const SegmentResultArea = styled.div`
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 12px;
  min-height: 120px;
`;

const SegmentTag = styled(Tag)<{ matched: boolean; selected: boolean }>`
  margin: 2px;
  padding: 4px 8px;
  border-radius: 3px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 11px;
  
  ${props => {
    if (props.selected) {
      return `
        background: #1890ff;
        color: white;
        border-color: #1890ff;
        transform: scale(1.05);
      `;
    } else if (props.matched) {
      return `
        background: #52c41a;
        color: white;
        border-color: #52c41a;
        
        &:hover {
          background: #73d13d;
          border-color: #73d13d;
          transform: translateY(-1px);
        }
      `;
    } else {
      return `
        background: #f0f0f0;
        color: #666;
        border-color: #d9d9d9;
        
        &:hover {
          background: #e6f7ff;
          border-color: #91d5ff;
          color: #1890ff;
          transform: translateY(-1px);
        }
      `;
    }
  }}
`;

/**
 * Category页面组件
 * 功能：显示服装类目数据，支持三列布局、多选、语言切换、分词和复制功能
 */
const Category: React.FC = () => {
  const [categories, setCategories] = useState<Category[]>([]);
  const [selectedItems, setSelectedItems] = useState<Set<string>>(new Set());
  const [language, setLanguage] = useState<'zh' | 'en' | 'th'>('zh');
  const [loading, setLoading] = useState(true);
  
  // 分词相关状态
  const [inputText, setInputText] = useState<string>('');
  const [unmatchedSegments, setUnmatchedSegments] = useState<string[]>([]);
  const [copyLanguage, setCopyLanguage] = useState<'zh' | 'en' | 'th'>('zh');

  /**
   * 加载类目数据
   */
  useEffect(() => {
    const loadCategories = async () => {
      try {
        // 并行加载三个数据源
        const [categoriesData, stylesData, fashionStylesData] = await Promise.all([
          import('../../mock/category/categories.json'),
          import('../../mock/category/styles.json'),
          import('../../mock/category/fashion_styles.json')
        ]);

        // 合并所有数据源
        const allCategories = [
          ...categoriesData.default,
          stylesData.default,
          fashionStylesData.default
        ];

        setCategories(allCategories);
      } catch (error) {
        message.error('加载数据失败');
        console.error('Error loading categories:', error);
      } finally {
        setLoading(false);
      }
    };

    loadCategories();
  }, []);

  /**
   * 处理项目选择
   */
  const handleItemSelect = (item: CategoryItem) => {
    const itemKey = `${item.zh}_${item.en}_${item.th}`;
    const newSelected = new Set(selectedItems);
    
    if (newSelected.has(itemKey)) {
      newSelected.delete(itemKey);
    } else {
      newSelected.add(itemKey);
    }
    
    setSelectedItems(newSelected);
  };

  /**
   * 获取选中项的翻译文本
   */
  const getSelectedText = (lang: 'zh' | 'en' | 'th' = copyLanguage): string => {
    const selectedTexts: string[] = [];
    
    categories.forEach(category => {
      category.items.forEach(item => {
        const itemKey = `${item.zh}_${item.en}_${item.th}`;
        if (selectedItems.has(itemKey)) {
          selectedTexts.push(item[lang]);
        }
      });
    });
    
    return selectedTexts.join(' ');
  };

  /**
   * 获取未匹配词语的文本
   */
  const getUnmatchedText = (): string => {
    return unmatchedSegments.join(',\n');
  };

  /**
   * 复制选中文本到剪贴板
   */
  const handleCopy = async () => {
    const text = getSelectedText();
    if (!text) {
      message.warning('请先选择要复制的项目');
      return;
    }

    try {
      await navigator.clipboard.writeText(text);
      message.success(`复制成功！(${copyLanguage === 'zh' ? '中文' : copyLanguage === 'en' ? 'English' : 'ไทย'})`);
    } catch (error) {
      message.error('复制失败，请手动复制');
    }
  };

  /**
   * 复制未匹配词语到剪贴板
   */
  const handleCopyUnmatched = async () => {
    const text = getUnmatchedText();
    if (!text) {
      message.warning('没有未匹配的词语可复制');
      return;
    }

    try {
      await navigator.clipboard.writeText(text);
      message.success('未匹配词语复制成功！');
    } catch (error) {
      message.error('复制失败，请手动复制');
    }
  };

  /**
   * 清空选择
   */
  const handleClearSelection = () => {
    setSelectedItems(new Set());
    message.info('已清空选择');
  };

  /**
   * 检查项目是否被选中
   */
  const isItemSelected = (item: CategoryItem): boolean => {
    const itemKey = `${item.zh}_${item.en}_${item.th}`;
    return selectedItems.has(itemKey);
  };

  /**
   * 检查分词结果是否与类目数据匹配
   */
  const isSegmentMatched = (segment: string): boolean => {
    return categories.some(category => 
      category.items.some(item => 
        item.zh.includes(segment) || 
        item.en.toLowerCase().includes(segment.toLowerCase()) ||
        item.th.includes(segment)
      )
    );
  };

  /**
   * 处理文本分词并自动匹配
   * 使用 segmentit 对输入文本进行中文分词，自动清除历史匹配并进行自动匹配
   */
  const handleSegmentAndMatch = async () => {
    if (!inputText.trim()) {
      message.warning('请输入要分词的文本');
      return;
    }

    try {
      // 1. 清除历史匹配
      setSelectedItems(new Set());
      
      // 2. 使用 segmentit 进行分词
      const { Segment, useDefault } = await import('segmentit');
      const segment = new Segment();
      useDefault(segment);
      
      const result = segment.doSegment(inputText.trim(), {
        simple: true
      });
      
      // 提取词语并过滤掉空字符串和标点符号
      const words = result.map((item: any) => item.w || item).filter((word: string) => 
        word.trim() && 
        word.length > 1 && 
        !/^[，。！？；：""''（）【】\s\d]+$/.test(word)
      );
      
      // 3. 自动匹配并选择类目项
      const newSelectedItems = new Set<string>();
      const unmatched: string[] = [];
      let matchCount = 0;

      words.forEach(word => {
        let hasMatch = false;
        categories.forEach(category => {
          category.items.forEach(item => {
            if (item.zh.includes(word) || 
                item.en.toLowerCase().includes(word.toLowerCase()) ||
                item.th.includes(word)) {
              const itemKey = `${item.zh}_${item.en}_${item.th}`;
              if (!newSelectedItems.has(itemKey)) {
                newSelectedItems.add(itemKey);
                matchCount++;
                hasMatch = true;
              }
            }
          });
        });
        
        if (!hasMatch) {
          unmatched.push(word);
        }
      });

      // 4. 更新状态
      setSelectedItems(newSelectedItems);
      setUnmatchedSegments(unmatched);
      
      message.success(`分词完成！匹配到 ${matchCount} 个类目项，${unmatched.length} 个词语未匹配`);
    } catch (error) {
      console.error('分词失败:', error);
      message.error('分词失败，请重试');
    }
  };

  /**
   * 清空分词结果
   */
  const handleClearSegments = () => {
    setInputText('');
    setUnmatchedSegments([]);
    message.info('已清空分词结果');
  };

  if (loading) {
    return (
      <PageContainer>
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Text>加载中...</Text>
        </div>
      </PageContainer>
    );
  }

  return (
    <PageContainer>
      {/* 头部控制区域 */}
      <HeaderSection>
        <Row justify="space-between" align="middle">
          <Col>
            <Title level={2} style={{ margin: 0 }}>
              服装类目选择器
            </Title>
            <Text type="secondary">
              选择您需要的服装类目，支持多选、多语言显示和智能分词匹配
            </Text>
          </Col>
          <Col>
            <Space>
              <Select
                value={language}
                onChange={setLanguage}
                style={{ width: 120 }}
              >
                <Option value="zh">中文</Option>
                <Option value="en">English</Option>
                <Option value="th">ไทย</Option>
              </Select>
              <Select
                value={copyLanguage}
                onChange={setCopyLanguage}
                style={{ width: 120 }}
                placeholder="复制语言"
              >
                <Option value="zh">复制中文</Option>
                <Option value="en">复制English</Option>
                <Option value="th">复制ไทย</Option>
              </Select>
              <Button 
                type="primary" 
                icon={<CopyOutlined />}
                onClick={handleCopy}
                disabled={selectedItems.size === 0}
              >
                复制选中项 ({selectedItems.size})
              </Button>
              <Button 
                onClick={handleCopyUnmatched}
                disabled={selectedItems.size === 0}
              >
                复制未匹配词语
              </Button>
              <Button 
                onClick={handleClearSelection}
                disabled={selectedItems.size === 0}
              >
                清空选择
              </Button>
            </Space>
          </Col>
        </Row>
      </HeaderSection>

      {/* 分词功能区域 - 左右布局 */}
      <SegmentSection>
        <Title level={4} style={{ marginBottom: 12, fontSize: '16px' }}>
          智能分词匹配
        </Title>
        <Row gutter={16}>
          <Col span={12}>
            <SegmentInputArea>
              <Text strong style={{ marginBottom: 8, display: 'block', fontSize: '13px' }}>
                输入文本：
              </Text>
              <TextArea
                placeholder="请输入要分词的句子，例如：我想要一件红色的短袖T恤和蓝色牛仔裤"
                value={inputText}
                onChange={(e) => setInputText(e.target.value)}
                rows={4}
                maxLength={500}
                showCount
                style={{ marginBottom: 8 }}
              />
              <Space size="small">
                <Button 
                  type="primary" 
                  size="small"
                  icon={<SearchOutlined />}
                  onClick={handleSegmentAndMatch}
                  disabled={!inputText.trim()}
                >
                  开始分词并匹配
                </Button>
                <Button 
                  size="small"
                  icon={<ClearOutlined />}
                  onClick={handleClearSegments}
                  disabled={unmatchedSegments.length === 0 && !inputText}
                >
                  清空结果
                </Button>
              </Space>
            </SegmentInputArea>
          </Col>
          <Col span={12}>
            <SegmentResultArea>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
                <Text strong style={{ fontSize: '13px' }}>
                  未匹配的词语：
                </Text>
                {unmatchedSegments.length > 0 && (
                  <Button 
                    size="small"
                    type="link"
                    icon={<CopyOutlined />}
                    onClick={handleCopyUnmatched}
                    style={{ padding: 0, height: 'auto' }}
                  >
                    复制
                  </Button>
                )}
              </div>
              {unmatchedSegments.length > 0 ? (
                <div>
                  {unmatchedSegments.map((segment, index) => (
                    <SegmentTag
                      key={index}
                      matched={false}
                      selected={false}
                    >
                      {segment}
                    </SegmentTag>
                  ))}
                </div>
              ) : (
                <Text type="secondary" style={{ fontSize: '12px' }}>
                  分词后未匹配的词语将显示在这里
                </Text>
              )}
            </SegmentResultArea>
          </Col>
        </Row>
      </SegmentSection>

      {/* 类目展示区域 - 三列布局 */}
      <Row gutter={[16, 16]}>
        {categories.map((category, index) => (
          <Col xs={24} sm={24} md={8} key={index}>
            <CategoryCard
              title={category.name[language]}
              size="small"
            >
              <div>
                {category.items.map((item, itemIndex) => (
                  <ItemTag
                    key={itemIndex}
                    selected={isItemSelected(item)}
                    onClick={() => handleItemSelect(item)}
                  >
                    {isItemSelected(item) && <CheckOutlined style={{ marginRight: 2 }} />}
                    {item[language]}
                  </ItemTag>
                ))}
              </div>
            </CategoryCard>
          </Col>
        ))}
      </Row>

      {/* 结果显示区域 */}
      {selectedItems.size > 0 && (
        <ResultSection>
          <Title level={4}>
            选中结果 ({copyLanguage === 'zh' ? '中文' : copyLanguage === 'en' ? 'English' : 'ไทย'})
          </Title>
          <ResultText>
            {getSelectedText() || '暂无选中项目'}
          </ResultText>
        </ResultSection>
      )}
    </PageContainer>
  );
};

export default Category;